package com.example.demo.service;

import com.example.demo.mapper.InviteCodeMapper;
import com.example.demo.model.InviteCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

@Service
public class InviteCodeService {
    private final InviteCodeMapper inviteCodeMapper;

    @Autowired
    public InviteCodeService(InviteCodeMapper inviteCodeMapper) {
        this.inviteCodeMapper = inviteCodeMapper;
    }

    /**
     * 为用户生成邀请码
     * @param creatorId 创建者用户ID
     * @return 生成的邀请码
     */
    @Transactional
    public String generateInviteCodeForUser(Long creatorId) {
        // 实时删除过期邀请码
        deleteExpiredInviteCodes();

        // 检查用户是否还能生成邀请码
        if (!canGenerateInviteCode(creatorId)) {
            throw new RuntimeException("已达到邀请码生成上限");
        }

        // 生成唯一邀请码
        String code = generateUniqueCode();

        // 创建邀请码对象
        InviteCode inviteCode = new InviteCode();
        inviteCode.setCode(code);
        inviteCode.setCreatorId(creatorId);
        inviteCode.setCreatedAt(LocalDateTime.now());
        inviteCode.setUsed(false);
        inviteCode.setExpiresAt(LocalDateTime.now().plusHours(24));

        // 保存到数据库
        inviteCodeMapper.insert(inviteCode);

        return code;
    }

    /**
     * 生成唯一的邀请码
     */
    private String generateUniqueCode() {
        return UUID.randomUUID().toString().replace("-", "").substring(0, 16);
    }

    /**
     * 验证邀请码是否有效并使用它
     */
    @Transactional
    public boolean validateAndUseInviteCode(String code, Long userId) {
        // 实时删除过期邀请码
        deleteExpiredInviteCodes();

        InviteCode inviteCode = inviteCodeMapper.findByCode(code);
        if (inviteCode == null || inviteCode.isUsed() || inviteCode.isExpired()) {
            return false;
        }

        // 标记邀请码为已使用
        inviteCode.setUsed(true);
        inviteCode.setUsedBy(userId);
        inviteCode.setUsedAt(LocalDateTime.now());
        inviteCodeMapper.update(inviteCode);

        return true;
    }

    /**
     * 检查用户是否可以生成邀请码
     */
    public boolean canGenerateInviteCode(Long creatorId) {
        // 默认配额10个
        return inviteCodeMapper.countByCreator(creatorId) < 10;
    }

    /**
     * 获取用户有效的邀请码列表
     */
    public List<InviteCode> getUserValidInviteCodes(Long creatorId) {
        return inviteCodeMapper.findValidCodesByCreator(creatorId);
    }

    /**
     * 根据邀请码查询
     */
    public InviteCode findByCode(String code) {
        return inviteCodeMapper.findByCode(code);
    }

    /**
     * 获取用户所有邀请码
     */
    public List<InviteCode> getAllInviteCodesByUser(Long creatorId) {
        return inviteCodeMapper.findAllCodesByCreator(creatorId);
    }

    /**
     * 获取用户已使用的邀请码
     */
    public List<InviteCode> getUsedInviteCodesByUser(Long creatorId) {
        return inviteCodeMapper.findUsedCodesByCreator(creatorId);
    }

    /**
     * 实时删除过期邀请码
     */
    @Transactional
    public void deleteExpiredInviteCodes() {
        inviteCodeMapper.deleteExpiredCodes(LocalDateTime.now());
    }
}